package com.example.interceptor;

import com.example.domain.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 资源拦截器
 */

public class ResourcesInterceptor extends HandlerInterceptorAdapter {


    private List<String> urls;

    public ResourcesInterceptor(List<String> urls) {
        this.urls = urls;
    }

    public ResourcesInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestUrl = request.getRequestURI();

        if (requestUrl.indexOf("login") > 0) {
            return true;
        }

          /*
            需要修改的地方
         */
        // 如果有用户登录，直接放行
//        Object user = request.getSession().getAttribute("USER_SESSION");
        User user = (User) request.getSession().getAttribute("USER_SESSION");

        if (user != null) {

            if ("ADMIN".equals(user.getRole())) {
                // 管理员 直接放行
                return true;
            } else {
                // 普通用户 判断后放行
                for (String url : urls) {
                    if (requestUrl.indexOf(url) > 0) {
                        return true;
                    }
                }

                request.setAttribute("msg", "权限不足");
                request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
                return false;

            }

        }

        // 如果不是登录相关，跳转到登录界面
        request.setAttribute("msg", "请先登录");
        request.getRequestDispatcher("/admin/login.jsp").forward(request, response);

        return false;
    }

}